package hn.cch.framework.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 使用fastjson
 * 使用jackson
 * 使用gson
 */
public class JsonUtil {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);


    public static String toStringFastJson(Object object) {
        // 字符串不处理
        if (object instanceof String) {
            return (String) object;
        }
        String string = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue);
        logger.debug("toStringFastJson:{}", string);
        return string;
    }

    public static <T> T toObjectFastJson(String string, Class<T> clazz) {
        logger.debug("toObjectFastJson:{}", string);
        assert string != null;
        T object = JSON.parseObject(string, clazz);
        return object;
    }


    public static String toStringJackson(Object object) {
        // 字符串不处理
        if (object instanceof String) {
            return (String) object;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String string = null;
        try {
            string = objectMapper.writeValueAsString(object);
            logger.debug("toStringJackson:{}", string);
        } catch (JsonProcessingException e) {
            logger.error("toStringJackson:{}", e.getMessage());
        }
        return string;
    }


    public static <T> T toObjectJackson(String string, Class<T> clazz) {
        logger.debug("toObjectJackson:{}", string);
        assert string != null;
        ObjectMapper objectMapper = new ObjectMapper();
        T object = null;
        try {
            object = objectMapper.readValue(string, clazz);
        } catch (IOException e) {
            logger.error("toObjectJackson:{}", e.getMessage());
        }
        return object;
    }


}
